package cn.wgd.zmx.service;

import cn.wgd.zmx.domain.Menu;
import cn.wgd.zmx.mapper.MenuMapper;
import cn.wgd.zmx.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuService {

    @Autowired
    private MenuMapper menuMapper;

    public List<TreeNode> getMenuByRole(String role){
        List<Menu> menus = menuMapper.selectByRole(role);

        List<TreeNode> nodes = new ArrayList<>();
        for(Menu menu:menus){
            /*先查询出所有父级菜单*/
            if(menu.getParentId()==0){

                TreeNode node = new TreeNode();

                node.setName(menu.getName());
                node.setUrl(menu.getUrl());
                if(!menu(menu.getId(), node)){
                    continue;
                }else{
                    nodes.add(node);
                }
            }
        }
        return nodes;
    }
    public boolean menu(Integer id,TreeNode node){
        /*先判断该父级菜单有没有子级菜单*/
        List<Menu> menus = menuMapper.selectByParentId(id);
        List<TreeNode> childs = new ArrayList<>();
        if(menus==null){
            return false;
        }else{
            /*遍历出每个节点，加入node属性*/
            for(Menu m:menus){
                TreeNode child = new TreeNode();
                child.setName(m.getName());
                child.setUrl(m.getUrl());
                childs.add(child);
            }
            node.setChild(childs);
        }
        return true;
    }
}
